<template>
  <div class="role-management-container">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h1 class="text-2xl font-bold text-gray-800">角色管理</h1>
      <p class="text-gray-500 mt-1">管理系统角色及角色默认权限</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar bg-white rounded-lg shadow-sm p-4 mb-6">
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <!-- 搜索框 -->
        <div class="relative w-full md:w-64">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索角色..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
            @keyup.enter="fetchRoles"
          >
          <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        </div>

        <!-- 操作按钮 -->
        <button
          class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-2 ml-auto"
          @click="showAddRoleModal = true"
        >
          <i class="fa fa-plus"></i>
          <span>新增角色</span>
        </button>
      </div>
    </div>

    <!-- 角色列表 -->
    <div class="role-list bg-white rounded-lg shadow-sm overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                角色名称
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                角色编码
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                描述
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                用户数量
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <template v-if="loading">
              <tr v-for="i in 5" :key="i" class="animate-pulse">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-32"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-24"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-64"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-12"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-16"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right">
                  <div class="h-8 bg-gray-200 rounded w-32 ml-auto"></div>
                </td>
              </tr>
            </template>

            <template v-else-if="roles.length === 0">
              <tr>
                <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                  <div class="flex flex-col items-center">
                    <i class="fa fa-users-cog text-4xl mb-3 text-gray-300"></i>
                    <p>没有找到匹配的角色</p>
                    <button
                      class="mt-2 text-indigo-600 hover:text-indigo-800 text-sm"
                      @click="resetSearch"
                    >
                      清除搜索
                    </button>
                  </div>
                </td>
              </tr>
            </template>

            <template v-else>
              <tr 
                v-for="role in roles" 
                :key="role.id"
                class="hover:bg-gray-50 transition-colors"
              >
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <div class="h-10 w-10 rounded-full bg-indigo-100 flex items-center justify-center mr-3">
                      <i class="fa fa-user-tag text-indigo-600"></i>
                    </div>
                    <div class="text-sm font-medium text-gray-900">{{ role.name }}</div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-500 font-mono">{{ role.code }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900">{{ role.description || '-' }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-900">{{ role.userCount }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="role.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
                  >
                    {{ role.status === 'active' ? '启用' : '禁用' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button
                    class="text-blue-600 hover:text-blue-900 mr-3"
                    @click="editRole(role)"
                    :disabled="role.isSystemRole"
                  >
                    编辑
                  </button>
                  <button
                    class="text-purple-600 hover:text-purple-900 mr-3"
                    @click="manageRolePermissions(role)"
                  >
                    权限
                  </button>
                  <button
                    class="text-red-600 hover:text-red-900"
                    @click="confirmStatusChange(role)"
                    :disabled="role.isSystemRole"
                  >
                    {{ role.status === 'active' ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-3 border-t border-gray-200 flex items-center justify-between">
        <div class="text-sm text-gray-500">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalRoles) }} 条，共 {{ totalRoles }} 条
        </div>
        <div class="flex space-x-2">
          <button
            class="px-3 py-1 border border-gray-300 rounded-md text-sm"
            :disabled="currentPage === 1"
            @click="currentPage = currentPage - 1"
          >
            上一页
          </button>
          <button
            class="px-3 py-1 border border-gray-300 rounded-md text-sm"
            :disabled="currentPage >= totalPages"
            @click="currentPage = currentPage + 1"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑角色模态框 -->
    <EditRoleModal
      :visible="showEditRoleModal"
      :role="selectedRole"
      @close="showEditRoleModal = false"
      @save="handleSaveRole"
    />

    <!-- 添加角色模态框 -->
    <AddRoleModal
      :visible="showAddRoleModal"
      @close="showAddRoleModal = false"
      @save="handleAddRole"
    />

    <!-- 角色权限管理模态框 -->
    <RolePermissionModal
      :visible="showPermissionModal"
      :role="selectedRole"
      :permissions="allPermissions"
      @close="showPermissionModal = false"
      @save="handleSaveRolePermissions"
    />

    <!-- 确认操作模态框 -->
    <ConfirmModal
      :visible="showConfirmModal"
      :title="confirmTitle"
      :message="confirmMessage"
      @close="showConfirmModal = false"
      @confirm="handleConfirmAction"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import EditRoleModal from './components/EditRoleModal.vue';
import AddRoleModal from './components/AddRoleModal.vue';
import RolePermissionModal from './components/RolePermissionModal.vue';
import ConfirmModal from '@/components/ConfirmDialog.vue';
import { useRoleStore } from '@/stores/roleStore';
import { usePermissionStore } from '@/stores/permissionStore';

export default {
  components: {
    EditRoleModal,
    AddRoleModal,
    RolePermissionModal,
    ConfirmModal
  },
  setup() {
    // 状态管理
    const roleStore = useRoleStore();
    const permissionStore = usePermissionStore();

    // 数据状态
    const roles = ref([]);
    const allPermissions = ref([]);
    const loading = ref(false);
    const totalRoles = ref(0);
    
    // 筛选状态
    const searchQuery = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    
    // 模态框状态
    const showEditRoleModal = ref(false);
    const showAddRoleModal = ref(false);
    const showPermissionModal = ref(false);
    const showConfirmModal = ref(false);
    const selectedRole = ref(null);
    const roleToChange = ref(null);
    
    // 确认框信息
    const confirmTitle = ref('');
    const confirmMessage = ref('');

    // 计算属性
    const totalPages = computed(() => {
      return Math.ceil(totalRoles.value / pageSize.value);
    });

    // 获取角色列表
    const fetchRoles = async () => {
      try {
        loading.value = true;
        const params = {
          page: currentPage.value,
          limit: pageSize.value,
          search: searchQuery.value
        };
        
        const response = await roleStore.getRoles(params);
        roles.value = response.data;
        totalRoles.value = response.total;
      } catch (error) {
        console.error('获取角色列表失败:', error);
        // 可以在这里添加错误提示
      } finally {
        loading.value = false;
      }
    };

    // 获取所有权限
    const fetchPermissions = async () => {
      try {
        const response = await permissionStore.getAllPermissions();
        allPermissions.value = response;
      } catch (error) {
        console.error('获取权限列表失败:', error);
      }
    };

    // 初始化数据
    const initData = async () => {
      await Promise.all([
        fetchRoles(),
        fetchPermissions()
      ]);
    };

    // 编辑角色
    const editRole = (role) => {
      selectedRole.value = { ...role };
      showEditRoleModal.value = true;
    };

    // 管理角色权限
    const manageRolePermissions = async (role) => {
      try {
        selectedRole.value = { ...role };
        // 获取角色当前权限
        const rolePermissions = await permissionStore.getRolePermissions(role.id);
        selectedRole.value.permissions = rolePermissions;
        showPermissionModal.value = true;
      } catch (error) {
        console.error('获取角色权限失败:', error);
      }
    };

    // 确认更改角色状态
    const confirmStatusChange = (role) => {
      roleToChange.value = role;
      const action = role.status === 'active' ? '禁用' : '启用';
      confirmTitle.value = `${action}角色`;
      confirmMessage.value = `确定要${action}角色 "${role.name}" 吗？${action === '禁用' ? '禁用后使用该角色的用户可能会受到影响。' : ''}`;
      showConfirmModal.value = true;
    };

    // 处理确认操作
    const handleConfirmAction = async () => {
      if (!roleToChange.value) return;

      try {
        const newStatus = roleToChange.value.status === 'active' ? 'inactive' : 'active';
        await roleStore.updateRoleStatus(roleToChange.value.id, newStatus);
        // 刷新角色列表
        fetchRoles();
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新角色状态失败:', error);
        // 可以在这里添加错误提示
      } finally {
        showConfirmModal.value = false;
        roleToChange.value = null;
      }
    };

    // 保存角色编辑
    const handleSaveRole = async (updatedRole) => {
      try {
        await roleStore.updateRole(updatedRole.id, updatedRole);
        // 刷新角色列表
        fetchRoles();
        showEditRoleModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新角色失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 添加新角色
    const handleAddRole = async (newRole) => {
      try {
        await roleStore.createRole(newRole);
        // 刷新角色列表
        fetchRoles();
        showAddRoleModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('创建角色失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 保存角色权限
    const handleSaveRolePermissions = async (roleId, permissions) => {
      try {
        await permissionStore.updateRolePermissions(roleId, permissions);
        showPermissionModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新角色权限失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 重置搜索
    const resetSearch = () => {
      searchQuery.value = '';
      currentPage.value = 1;
      fetchRoles();
    };

    // 页面加载时初始化
    onMounted(() => {
      initData();
    });

    return {
      roles,
      allPermissions,
      loading,
      totalRoles,
      searchQuery,
      currentPage,
      pageSize,
      totalPages,
      showEditRoleModal,
      showAddRoleModal,
      showPermissionModal,
      showConfirmModal,
      selectedRole,
      confirmTitle,
      confirmMessage,
      fetchRoles,
      editRole,
      manageRolePermissions,
      confirmStatusChange,
      handleConfirmAction,
      handleSaveRole,
      handleAddRole,
      handleSaveRolePermissions,
      resetSearch
    };
  }
};
</script>

<style scoped>
.role-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar .flex {
    flex-direction: column;
    align-items: stretch;
  }
  
  .role-list table {
    font-size: 14px;
  }
  
  .role-list th,
  .role-list td {
    padding: 8px 12px;
  }
}
</style>
    